﻿using BusinessManage.Common;
using CPFrameWork.Global;
using CPFrameWork.UIInterface.Grid;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using static CPFrameWork.UIInterface.Grid.GridEngineController;
using NLog;
using CPFrameWork.Utility.DbOper;

namespace BusinessManage.OrderFormCable
{
    /**
     * Author：WANGYY
     * DESC：排线
     * **/
    public class OrderFormCableController : CPWebApiBaseController
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        [HttpPost]
        public CPWebApiBaseReturnEntity SetTaskCar([FromBody] TaskCarRelation taskCarRelation)
        {
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {
                int CurUserId = Convert.ToInt32(taskCarRelation.CurUserId);
                string CurUserIden = taskCarRelation.CurUserIden;
                string GridCode = taskCarRelation.GridCode;
                if (this.CheckUserIden(CurUserId, CurUserIden) == false)
                {
                    re.Result = false;
                    re.ErrorMsg = "登陆超时，请退出重新登陆！";
                    return re;
                }
               
                OrderFormCable orderFormCable = new OrderFormCable();
                IList<CarIds> CarIds = taskCarRelation.CarIds;
                string OrderIds = taskCarRelation.OrderIds;
                string Sorts = taskCarRelation.Sorts;
                string HallIds = taskCarRelation.HallIds;
                string taskIdD = taskCarRelation.TaskID;
                //设置车辆
                if (CarIds != null && CarIds.Count > 0 && OrderIds == null && HallIds == null && taskIdD != null)
                {
                    re = orderFormCable.DeleteYW_TaskCarRelation(taskIdD, CurUserId, GridCode);
                    //更新任务分配车辆表信息
                    DataTable dt = orderFormCable.GetYW_TaskOrderRelation(taskIdD, CurUserId, GridCode);
                    foreach (DataRow dataRow in dt.Rows)
                    {
                        foreach (CarIds car in CarIds)
                        {
                            DataTable mainuserTable = orderFormCable.GetCP_User(car.MainDriverID, CurUserId, GridCode);
                            DataTable assuserTable = orderFormCable.GetCP_User(car.AssistantDriverId, CurUserId, GridCode);
                            re = orderFormCable.SaveYW_TaskCarRelation(dataRow,CurUserId,GridCode,mainuserTable,assuserTable, car.DataPK,car.BuyClickCount,car.HallLossCount);
                        }
                    }
                    re.ErrorMsg = taskIdD;
                    return re;
                }
                //string[] carArray = CarIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                string[] orderArray = new string[0], hallArray = new string[0];
                if (OrderIds != null) orderArray = OrderIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (HallIds != null) hallArray = HallIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                string[] sortArray = Sorts.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                DataTable orderdt = orderFormCable.GetOrderInfo(CurUserId, OrderIds, HallIds, GridCode);

                /// 调整任务信息  
                //if (taskIdD != "" && taskIdD != null && taskIdD != "null")
                //    re = orderFormCable.DeleteTaskInfoRelation(taskIdD, CurUserId, GridCode);
                //else
                if (taskIdD == "" || taskIdD == null || taskIdD == "null")
                    taskIdD = orderFormCable.SaveYW_TaskInfo(orderdt, CurUserId, GridCode);
                if (orderArray == null || orderArray.Length == 0) orderArray = hallArray;
                for (int i=0;i<orderArray.Length;i++)
                {
                    string orderid = string.Empty, hallid = string.Empty;
                    if (OrderIds != null) orderid = orderArray[i];
                    if (HallIds != null) hallid = hallArray[i];
                    string sort = "1";
                    if (sortArray[i] != "NaN")
                        sort = sortArray[i];
                    DataRow[] dataRows;
                    if (HallIds != "" && HallIds != null) dataRows = orderdt.Select("code=" + hallid);
                    else dataRows = orderdt.Select("id=" + orderid);
                    List<long> TaskOrder=new List<long>();
                    re = orderFormCable.SaveYW_TaskOrderRelation(dataRows, taskIdD, CurUserId, GridCode, sort,ref TaskOrder);
                    #region 清空原来的车辆信息，重新设置
                    orderFormCable.ClearTaskCar(CurUserId, GridCode, dataRows,  taskIdD, TaskOrder);
                    #endregion
                    foreach (CarIds carid in CarIds)
                    {
                        DataTable mainuserTable = orderFormCable.GetCP_User(carid.MainDriverID,CurUserId,GridCode);
                        DataTable assuserTable = orderFormCable.GetCP_User(carid.AssistantDriverId, CurUserId, GridCode);
                        re = orderFormCable.SetYW_TaskCarRelation(carid.DataPK, CurUserId, GridCode, dataRows, taskIdD, mainuserTable, assuserTable,carid.BuyClickCount,carid.HallLossCount, TaskOrder);
                    }
                    //处理YW_TaskOrderRelation表中的CarNumber表数据
                    orderFormCable.updateCarNumberForYW_TaskCarRelation(taskIdD, TaskOrder, CurUserId, GridCode);
                    //订单操作日志
                    OrderOperateLog orderOperateLog = new OrderOperateLog()
                    {
                        DbIns = "CPYKWL",
                        LinkType = "30",
                        LinkName = "订单排线",
                        orderid = dataRows[0]["OrderCode"].ToString(),
                        taskid= taskIdD,
                        OperateName="设置车辆"
                    };
                    OrderLog.OrderOperateLog(orderOperateLog);
                }
                re.ErrorMsg = taskIdD;
                return re;
            }
            catch (Exception ex)
            {
                re.Result = false;
                _logger.Error(string.Format("【订单排线】排线操作，发生异常异常信息为{0}", ex.Message));
                re.ErrorMsg = ex.Message.ToString();
                return re;
            }

        }

        /// <summary>
        /// 单独设施车辆
        /// </summary>
        /// <param name="taskCarRelation"></param>
        /// <returns></returns>
        [HttpPost]
        public CPWebApiBaseReturnEntity SetUpdateTaskCar([FromBody] TaskCarRelation taskCarRelation)
        {
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {
                int CurUserId = Convert.ToInt32(taskCarRelation.CurUserId);
                string CurUserIden = taskCarRelation.CurUserIden;
                string GridCode = taskCarRelation.GridCode;
                if (this.CheckUserIden(CurUserId, CurUserIden) == false)
                {
                    re.Result = false;
                    re.ErrorMsg = "登陆超时，请退出重新登陆！";
                    return re;
                }

                OrderFormCable orderFormCable = new OrderFormCable();
                IList<CarIds> CarIds = taskCarRelation.CarIds;
                string OrderIds = taskCarRelation.OrderIds;
                string Sorts = taskCarRelation.Sorts;
                string HallIds = taskCarRelation.HallIds;
                string taskIdD = taskCarRelation.TaskID;
                //设置车辆
                if (CarIds != null && CarIds.Count > 0 && OrderIds == "" && HallIds == "" && taskIdD != "")
                {
                    re = orderFormCable.DeleteYW_TaskCarRelation(taskIdD, CurUserId, GridCode);
                    //更新任务分配车辆表信息
                    DataTable dt = orderFormCable.GetYW_TaskOrderRelation(taskIdD, CurUserId, GridCode);
                    foreach (DataRow dataRow in dt.Rows)
                    {
                        foreach (CarIds car in CarIds)
                        {
                            DataTable mainuserTable = orderFormCable.GetCP_User(car.MainDriverID, CurUserId, GridCode);
                            DataTable assuserTable = orderFormCable.GetCP_User(car.AssistantDriverId, CurUserId, GridCode);
                            re = orderFormCable.SaveYW_TaskCarRelation(dataRow, CurUserId, GridCode, mainuserTable, assuserTable, car.DataPK, car.BuyClickCount, car.HallLossCount);
                        }
                        //处理YW_TaskOrderRelation表中的CarNumber表数据
                        List<long> TaskOrder = new List<long>();
                        TaskOrder.Add(Convert.ToInt64( dataRow["Id"]));
                        orderFormCable.updateCarNumberForYW_TaskCarRelation(taskIdD, TaskOrder, CurUserId, GridCode);
                    }
       

                }
                re.ErrorMsg = taskIdD;
                return re;
            }
            catch (Exception ex)
            {
                re.Result = false;
                _logger.Error(string.Format("【订单排线】单独设施车辆，发生异常异常信息为{0}", ex.Message));
                re.ErrorMsg = ex.Message.ToString();
                return re;
            }

        }

        [HttpGet]
        public string GetPrimarykeySource(string GridCode, int CurUserId, string CurUserIden)
        {
            OrderFormCable orderFormCable = new OrderFormCable();
            CPGrid Grid = CPGridEngine.Instance(CurUserId).GetGrid(GridCode, true, true);
            CPGridClient cpgrid = AutoMapper.Mapper.Map<CPGridClient>(Grid);
            return JsonConvert.SerializeObject(orderFormCable.ReadPrimarykeyListDataAndFormat(cpgrid));
        }
        /// <summary>
        /// 删除任务下面的订单
        /// </summary>
        /// <param name="orderCarRelation"></param>
        /// <returns></returns>
        [HttpPost]
        public CPWebApiBaseReturnEntity DelOrderANDCarForTask([FromBody] OrderCarRelation orderCarRelation)
        {

            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {

                int CurUserId = Convert.ToInt32(orderCarRelation.CurUserId);
                string CurUserIden = orderCarRelation.CurUserIden;
                string GridCode = orderCarRelation.GridCode;
                if (this.CheckUserIden(CurUserId, CurUserIden) == false)
                {
                    re.Result = false;
                    re.ErrorMsg = "登陆超时，请退出重新登陆！";
                    return re;
                }
                OrderFormCable orderFormCable = new OrderFormCable();
                string OrderIds = orderCarRelation.Order_Id;
                string taskIdD = orderCarRelation.TaskID;

                DataTable orderdt = orderFormCable.GetYW_GivetohallInfo(CurUserId, OrderIds, GridCode);

                string[] orderArray = OrderIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                for (int i=0;i< orderdt.Rows.Count; i++)
                {
                    string hallid = (orderdt.Rows[i]["Id"]).ToString();
                    re = orderFormCable.DeleteTaskInfoRelation(taskIdD, hallid, CurUserId, GridCode); 
                }

                re.Result = true;
                return re;
            }
            catch (Exception ex)
            {
                re.Result = false;
                _logger.Error(string.Format("【订单排线】 删除任务下面的订单，发生异常异常信息为{0}", ex.Message));
                re.ErrorMsg = ex.Message.ToString();
                return re;
            }
        }

        /// <summary>
        /// 保存订单信息
        /// </summary>
        /// <param name="orderRelation"></param>
        /// <returns></returns>
        [HttpPost]
        public CPWebApiBaseReturnEntity saveOrderForTask([FromBody] OrderRelation orderRelation)
        {
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {
                int CurUserId = Convert.ToInt32(orderRelation.CurUserId);
                string CurUserIden = orderRelation.CurUserIden;
                string GridCode = orderRelation.GridCode;
                if (this.CheckUserIden(CurUserId, CurUserIden) == false)
                {
                    re.Result = false;
                    re.ErrorMsg = "登陆超时，请退出重新登陆！";
                    return re;
                }
                OrderFormCable orderFormCable = new OrderFormCable();
                string OrderIds = orderRelation.OrderIds;
                string Sorts = orderRelation.Sorts;
                string taskIdD = orderRelation.TaskID;

                string[] orderArray = OrderIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                Sorts = Sorts.Replace("$", ",");
                string[] sortArray = Sorts.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
               


                if (taskIdD == "" || taskIdD == null || taskIdD == "null")
                {
                    DataTable orderdata = orderFormCable.GetOrderInfo(CurUserId, OrderIds, "", GridCode);
                    taskIdD = orderFormCable.SaveYW_TaskInfo(orderdata, CurUserId, GridCode);
                }

                for (int i = 0,j=0; i < orderArray.Length; i++)
                {

                    string id = orderArray[i];
                    DataTable orderdt = orderFormCable.GetYW_GivetohallInfo(CurUserId, id, GridCode);
                    
                    foreach (DataRow dataRow in orderdt.Rows)
                    {
                        string orderid = (dataRow["OrderId"]).ToString();
                        string hallid = (dataRow["Id"]).ToString();
                        int sortid = j > sortArray.Length - 1 ? Convert.ToInt32(sortArray[sortArray.Length - 1]) : Convert.ToInt32(sortArray[j]);
                        re = orderFormCable.SaveOrderForTaskInfoRelation(taskIdD, orderid, hallid, sortid, CurUserId, GridCode, dataRow);
                        //订单操作日志
                        OrderOperateLog orderOperateLog = new OrderOperateLog()
                        {
                            DbIns = "CPYKWL",
                            LinkType = "30",
                            LinkName = "订单排线",
                            orderid = orderid,
                            taskid = taskIdD,
                            OperateName= "保存订单信息"
                        };
                        OrderLog.OrderOperateLog(orderOperateLog);
                        j++;
                    }
                   
                }
                re.Result = true;
                return re;
            }
            catch (Exception ex)
            {
                re.Result = false;
                _logger.Error(string.Format("【订单排线】保存订单信息，发生异常异常信息为{0}",ex.Message));
                re.ErrorMsg = ex.Message.ToString();
                return re;
            }
        }

        [HttpPost]
        public string GetTaskOrderList([FromBody] string taskid)
        {
            OrderFormCable orderFormCable = new OrderFormCable();          
            return JsonConvert.SerializeObject(orderFormCable.CustomerAddressForTaskid(taskid));
        }

        [HttpGet]
        public string GetCP_DepList()
        {
            string dep= CPFrameWork.Global.CPExpressionHelper.Instance.RunCompile("${CPUser.DepIds()}");          
            OrderFormCable orderFormCable = new OrderFormCable();
            return JsonConvert.SerializeObject(orderFormCable.GetCP_Dep(dep));
        }
        /// <summary>
        /// 调整DeliveryTaskStatus状态值
        /// </summary>
        /// <param name="taskid"></param>
        /// <param name="DeliveryTaskStatus"></param>
        /// <returns></returns>
        [HttpPost]
        public CPWebApiBaseReturnEntity AdjustDeliveryTaskStatus([FromBody] UpdateObj updateObj)
        {
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {
                int CurUserId = Convert.ToInt32(updateObj.CurUserId);
                string CurUserIden = updateObj.CurUserIden;
                string GridCode = updateObj.GridCode;
                if (this.CheckUserIden(CurUserId, CurUserIden) == false)
                {
                    re.Result = false;
                    re.ErrorMsg = "登陆超时，请退出重新登陆！";
                    return re;
                }
                CPGrid grid = CPGridEngine.Instance(CurUserId).GetGrid(GridCode, false, false);
                DbHelper dbHelper = new DbHelper(grid.DbIns, CPAppContext.CurDbType());

                #region 审核发车状态
                string taskid = updateObj.taskid;
                string carNumber = updateObj.carNumber;
                int CarDeliveryTaskStatus = updateObj.CarDeliveryTaskStatus;
                StringBuilder stringB = new StringBuilder();
                string carStateSql = @"update  dbo.YW_TaskCarRelation set CarDeliveryTaskStatus=" + CarDeliveryTaskStatus + " where taskid='" + taskid + "' and  CarNumber='" + carNumber + "'";
                if (stringB.Length > 0)
                    stringB.Append(";");
                stringB.Append(carStateSql);
                dbHelper.ExecuteNonQuery(stringB.ToString());
                #endregion


                #region 任务状态

                int DeliveryTaskStatus = updateObj.DeliveryTaskStatus;

                StringBuilder sb = new StringBuilder();
                string sql = string.Empty;
                if (DeliveryTaskStatus == -1)
                    sql = @" IF  not  EXISTS (SELECT  * FROM dbo.YW_TaskInfo where TaskId='20181113000019' and DeliveryTaskStatus=-1   ) 
                                              update dbo.YW_TaskInfo set DeliveryTaskStatus=-1 where taskid='" + taskid + "'";
                else
                {
                    StringBuilder sbuilder = new StringBuilder();
                    string judgesql = @" SELECT  COUNT(0) totalsum,(select COUNT(0) from dbo.YW_TaskCarRelation where w.TaskId=TaskId and  CarDeliveryTaskStatus=0 group by TaskId) statussum 
                                         FROM dbo.YW_TaskCarRelation w where TaskId='"+ taskid + "'  group by TaskId";
                    if (sbuilder.Length > 0)
                        sbuilder.Append(";");
                    sbuilder.Append(judgesql);
                    
                    DataTable taskcardt = dbHelper.ExecuteDataSet(sbuilder.ToString()).Tables[0];
                    if (taskcardt.Rows.Count > 0)
                    {
                        if (Convert.ToInt32(taskcardt.Rows[0]["totalsum"]) == Convert.ToInt32(taskcardt.Rows[0]["statussum"]))
                            sql = " update dbo.YW_TaskInfo set DeliveryTaskStatus=0 where taskid='" + taskid + "'";
                        
                    }
                    
                }
                if (sb.Length > 0)
                    sb.Append(";");
                sb.Append(sql);

                if (sb.Length > 0)
                {
                    System.Diagnostics.Debug.WriteLine(sb.ToString());
                    dbHelper.ExecuteNonQuery(sb.ToString());
                }

                #endregion

                re.Result = true;
                return re;
            }
            catch (Exception ex)
            {
                re.Result = false;
                _logger.Error(string.Format("【排线审核】发生异常，异常信息为{0}", ex.Message));
                re.ErrorMsg = ex.Message.ToString();
                return re;
            }
            }

        /// <summary>
        /// 删除订单排线
        /// </summary>
        /// <param name="pkFieldValue"></param>
        /// <param name="CurUserId"></param>
        /// <param name="CurUserIden"></param>
        /// <returns></returns>
        [HttpGet]
        public CPWebApiBaseReturnEntity DeleteTreeData(string pkFieldValue, int CurUserId, string CurUserIden)
        {
            base.SetHeader();
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            if (this.CheckUserIden(CurUserId, CurUserIden) == false)
            {
                re.Result = false;
                re.ErrorMsg = "登陆超时，请退出重新登陆！";
                return re;
            }
            try
            {
                string[] taskArray = pkFieldValue.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (taskArray.Length == 2)//任务
                {
                    _logger.Info(string.Format("【订单排线】删除任务信息，参数为{0}", pkFieldValue));
                    OrderFormCable orderFormCable = new OrderFormCable();
                    re = orderFormCable.DeleteTaskInfo(taskArray[1]);
                    return re;
                }
                if (taskArray.Length == 3)//任务下车辆
                {
                    _logger.Info(string.Format("【订单排线】删除任务下指定车辆信息，参数为{0}", pkFieldValue));
                    OrderFormCable orderFormCable = new OrderFormCable();
                    re = orderFormCable.DeleteTaskCarRelationInfo(taskArray[1],taskArray[2]);
                    return re;
                }
                if (taskArray.Length == 4)//任务下订单
                {
                    _logger.Info(string.Format("【订单排线】删除任务下指定订单，参数为{0}", pkFieldValue));
                    OrderFormCable orderFormCable = new OrderFormCable();
                    re = orderFormCable.DeleteTaskOrderRelationInfo(taskArray[1], taskArray[2], taskArray[3]);
                    return re;
                }
            
                re.Result = true;
                return re;
            }
            catch (Exception ex)
            {
                re.Result = false;
                _logger.Error(string.Format("【订单排线】删除订单排线树中数据发生异常，异常信息为{0}",ex.Message));
                re.ErrorMsg = ex.Message.ToString();
                return re;
            }
        }


    }

    /**
     * Author：WANGYY
     * DESC：订单调整
     * **/

    public class OrderChangeController : CPWebApiBaseController
    {
        [HttpPost]
        public CPWebApiBaseReturnEntity SubmitOrderChange([FromBody]OrderChange orderChange)
        {
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {

                int CurUserId = Convert.ToInt32(orderChange.CurUserId);
                string CurUserIden = orderChange.CurUserIden;
                string GridCode = orderChange.GridCode;
                if (this.CheckUserIden(CurUserId, CurUserIden) == false)
                {
                    re.Result = false;
                    re.ErrorMsg = "登陆超时，请退出重新登陆！";
                    return re;
                }
                string oldTaskId = orderChange.oldTaskId;
                string newOrderIds = orderChange.newOrderIds;
                string[] oldTaskArray = new string[0], newOrderArray = new string[0];
                if (newOrderIds != string.Empty) newOrderArray = newOrderIds.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries);
                OrderFormCable orderFormCable = new OrderFormCable();
                DataTable dt = orderFormCable.GetYW_TaskOrderRelation(oldTaskId, CurUserId, GridCode);

                foreach(DataRow dr in dt.Rows)
                {
                    string taskid = dr["TaskId"].ToString();
                    string oldOrderId = dr["OrderId"].ToString();
                    for (int i=0;i< newOrderArray.Length;i++)
                    {
                        re = orderFormCable.SaveYW_TaskChangeRelation(taskid, oldOrderId, newOrderArray[i].ToString());
                    }
                }

                return re;
            }
            catch (Exception ex)
            {
                re.Result = false;
                re.ErrorMsg = ex.Message.ToString();
                return re;
            }
        }

    }
}
